#encoding=utf8
import json
import re,os
import traceback
from wox import Wox,WoxAPI

class Shadowsocks(Wox):

    def get_config(self)->dict:
        with open(os.path.join(os.path.dirname(__file__),"config.json"), "r") as content_file:
            config = json.loads(content_file.read())
            return config
            

    def add_new_domain(self,domain):
        if not domain:
            WoxAPI.show_msg("Warning","You can't add empty domain")
            return
        config = self.get_config()
        pacPath = config['pacPath']
        pattern = config['pattern']
        
        with open(pacPath,'r') as f:
            pac = f.read() 
        p = pac.find(pattern)
        p += len(pattern)
        pac = pac[:p] + f'\n\t"{domain}",' + pac[p:]
        with open(pacPath,'w') as f:
            f.write(pac)

    def query(self,query):
        res = []
        res.append({
            "Title": "add {} to Shadowsocks PAC list".format(query),
            "IcoPath":"ssw.png",
            "JsonRPCAction":{"method": "add_new_domain", "parameters": [query]}
            })
        return res

if __name__ == "__main__":
    Shadowsocks()
